import {arrayProp, index, ModelType, pre, prop, Ref, Typegoose} from "typegoose";
import {Player} from "./player";
import {Product} from "./Product";
import {SeriesIncomeThresholdModel} from "./seriesIncomeThreshold";

async function updateSeriesIncomeThreshold(lipstickSeries) {
  try {
    await SeriesIncomeThresholdModel.findOneAndUpdate(
      {lipstickSeries: lipstickSeries._id},
      {$set: {updateAt: new Date()}},
      {upsert: true, setDefaultsOnInsert: true}
    )
  } catch (e) {
    console.log(e)
  }
}

@pre<LipstickSeries>(`save`, async function (next) {

  if (!this.products || this.products.length === 0)
    throw Error(`products 不能为空`)

  await updateSeriesIncomeThreshold(this)

  // await setStock(this)

  next()
})

export class LipstickSeries extends Typegoose {

  @prop({required: true})
  brand: string

  @prop({required: true})
  name: string

  @prop({required: true})
  seriesPrice: number

  @prop({required: true})
  underLinePrice: number // 划线价格

  @prop({required: true})
  priceInCoin: number

  @prop({required: true, default: 999})
  priceInFangka: number

  @prop({required: true})
  coverUrl: string

  @prop({required: true})
  description: string

  @prop({required: true, default: false})
  onStock: boolean

  @arrayProp({itemsRef: Product, required: true})
  products: Array<Ref<Product>>

  @prop({})
  details: string[]

  @prop({required: true, default: () => new Date()})
  createAt: Date

  @prop({required: true, default: () => new Date()})
  updateAt: Date

  @prop({required: true})
  category: 'lipstick' | 'pressAccurate'

  @prop({required: true, default: 50})
  sortNum: number

  @prop({required: true, default: 0})
  hotNum: number
}

@index({updateAt: -1})
export class SeriesIncome extends Typegoose {
  @prop({ref: LipstickSeries, required: true, unique: true})
  lipstickSeries: Ref<LipstickSeries>

  @prop({required: true})
  income: number

  @prop({required: true, default: () => new Date()})
  updateAt: Date
}

@index({updateAt: -1})
@index({player: 1, lipstickSeries: 1}, {unique: true})
export class PlayerSeriesIncome extends Typegoose {

  @prop({ref: Player, required: true})
  player: Ref<Player>

  @prop({ref: LipstickSeries, required: true})
  lipstickSeries: Ref<LipstickSeries>

  @prop({required: true})
  income: number

  @prop({required: true, default: () => new Date()})
  updateAt: Date
}

export const LipstickSeriesModel: ModelType<LipstickSeries> = new LipstickSeries().getModelForClass(LipstickSeries)
export const SeriesIncomeModel: ModelType<SeriesIncome> = new SeriesIncome().getModelForClass(SeriesIncome)
export const PlayerSeriesIncomeModel: ModelType<PlayerSeriesIncome> = new PlayerSeriesIncome().getModelForClass(PlayerSeriesIncome)
